package com.shuziren.webscoket;

import com.shuziren.service.RedisService;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.ArrayList;
import java.util.List;

public class SystemHandler extends TextWebSocketHandler {
    private final UserSessionRegistry userSessionRegistry;

    private final RedisService redisService;

    public SystemHandler(UserSessionRegistry userSessionRegistry, RedisService redisService) {
        this.userSessionRegistry = userSessionRegistry;
        this.redisService = redisService;
    }



    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接");
        // 从握手属性中获取用户ID（需在拦截器中注入）
        String userId = (String) session.getAttributes().get("userId");
        String token = (String)session.getAttributes().get("token");
        Object o = redisService.get("OnlineUser:" + userId);
        //去掉 "Bearer " 前缀
//        if (token.startsWith("Bearer ")) {
//            token = token.substring(7);
//        }
//        boolean equals = o.equals(token);
//        if (userId == null || !equals) {
//            session.close(CloseStatus.NOT_ACCEPTABLE.withReason("未认证用户"));
//            return;
//        }

        userSessionRegistry.registerSession(o.toString(),userId, session);
//        userSessionRegistry.registerSession("qwedsafrgtyh","1", session);
        // 连接建立后，主动向客户端发送一条欢迎消息，便于前端确认连接状态
        session.sendMessage(new TextMessage("欢迎你，用户 " + "1" + "，连接已建立！"));
        super.afterConnectionEstablished(session);
        List<Integer> list = new ArrayList<Integer>();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        String sessionId = session.getId();
        userSessionRegistry.unregisterSession(userId, sessionId);
        super.afterConnectionClosed(session, status);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 收到客户端消息后，原样回显给客户端，便于调试
        session.sendMessage(new TextMessage("服务端收到: " + message.getPayload()));
    }
}
